<?php

class CategoryController extends Controller
{
	public function actionIndex($id='',$page='1',$perpage='10',$order='1',$feature='',$manufacturer='',$pricerange=''){
        $meta = Category::model()->findbypk($id);
		$meta->viewcount = $meta['viewcount']+1;
		$meta->save();

		$requested_manufacturers = array();
		$requested_features = array();

		/*мета-данные*/
		echo CHtml::tag('title',array(),Category::model()->title($id, $page).CHtml::encode(Yii::app()->name))."\n";
		Yii::app()->clientScript->registerMetaTag(Category::model()->description($id), 'description');
		Yii::app()->clientScript->registerMetaTag(Category::model()->keywords($id), 'keywords');

		if($perpage != 10 || $order != 1 || $feature != '' || $manufacturer != '' || $pricerange != ''){
			Yii::app()->clientScript->registerMetaTag( "noindex", "robots", null);
			Yii::app()->clientScript->registerMetaTag( "nofollow", "robots", null);
		}
		/*мета-данные*/

		if($manufacturer){
			$requested_manufacturers = explode(':', $manufacturer);;
			$requested_manufacturers = array_unique($requested_manufacturers);
		}else{
			$requested_manufacturers = array();
		}

		if($feature){
			$requested_features = explode(':', $feature);
			$requested_features = array_unique($requested_features);
		}else{
			$requested_features = array();
		}

		$avalible_items = Yii::app()->db->createCommand()
			->select('id, manufacturer')
			->from('prefix_item')
			->where('category=:id', array(':id'=>$id))
			->queryAll();

		if($meta['parent'] == '0'){
            $childs = Yii::app()->db->createCommand()
                ->select('id,title')
                ->from('{{category}}')
                ->where('parent=:parent', array(':parent'=>$meta['id']));
            $childs->setFetchMode(PDO::FETCH_OBJ);
            $childs = $childs->queryAll();
			$this->breadcrumbs=array(
				$meta['title'],
			);
			$this->render('first', array('category' => $meta, 'childs' => $childs));
		}else{

			/*определение направления сортировки*/
			switch ($order) {
				case '1':
					$orderby = 'title DESC';
					break;
				case '2':
					$orderby = 'title ASC';
					break;
				case '3':
					$orderby = 'price DESC';
					break;
				case '4':
					$orderby = 'price ASC';
					break;
				default:
					$orderby = 'title DESC';
					break;
			}
			/*определение направления сортировки*/

			$criteria = new CDbCriteria();

			$criteria->compare('category',$meta['id']);

			if($manufacturer){
				$criteria->addInCondition('manufacturer', $requested_manufacturers);
			}

			if($feature){
				
			}

			$price['max'] = Item::model()->price_max()->find($criteria);
			$price['min'] = Item::model()->price_min()->find($criteria);
            if(isset($price['max'])){
                $price['max'] = $price['max']->price;
            }else{
                $price['max'] = 0;
            }
            if(isset($price['min'])){
                $price['min'] = $price['min']->price;
            }else{
                $price['min'] = 0;
            }
			$price['request_min'] = '';
			$price['request_max'] = '';

			if($pricerange){
				if(strstr($pricerange,':')){
					if(strpos($pricerange,':') == 0){
						$price['request_max'] = substr($pricerange, 1);
					}else{
						$prices = explode(':',$pricerange);
						$price['request_min'] = $prices[0];
						$price['request_max'] = $prices[1];
					}
				}else{
					$price['request_min'] = $pricerange;
				}
			}
			//TODO кривые границы. убрать это 99999999
			if($price['request_min'] == ''){ $price['request_min'] = 0; }
			if($price['request_max'] == ''){ $price['request_max'] = 9999999999999; }
			$criteria->addBetweenCondition('price', $price['request_min'], $price['request_max']);

			$criteria->order = $orderby;

			$count=Item::model()->count($criteria);
			$pages=new CPagination($count);
			$pages->pageSize=$perpage;
			$pages->applyLimit($criteria);
			$items = Item::model()->findAll($criteria);

			$parent = Category::model()->findbypk($meta['parent']);

			$this->breadcrumbs=array(
				$parent['title']=>array('category/index', 'id'=>$parent['id']),
				$meta['title'],
			);

            $this->yiistoRender('second', array(
        	    'category' => $meta,
        	    'parent' => $parent,
        		'id' => $meta['id'],
        		'items' => $items,
        		'pages' => $pages,
        		'count' => $count,
        		'page' => $page,
        		'price' => $price,
        		'perpage' => $perpage,
        		'order' => $order,
        		'manufacturer' => $manufacturer,
        		'requested_manufacturers' => $requested_manufacturers,
        		'feature' => $feature,
        		'requested_features' => $requested_features,
        		'avalible_items' => $avalible_items,
        		'criteria' => $criteria,
        	));
		}
	}

    public function actionStock(){
        echo "Акционные товары";
    }

    public function actionDiscount(){
        echo "Распродажа товаров";
    }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}